﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FoneBuddy.LinqData;
using FoneBuddy.LinqModel;
using FoneBuddy.LinqModel.Data;

public partial class MerchantPromotionCode : System.Web.UI.Page
{


    IDataRepository _dataObject = new DataRepository();
    protected void Page_Load(object sender, EventArgs e)
    {
        //Session["SubscriptionId"] = 30;
        //string id = Session["SubscriptionId"].ToString();
        if (!IsPostBack)
        {
            BindData();
        }
    }

    #region webmethod
    [System.Web.Services.WebMethod]
    public static string[] CheckPromotionCode(string Code)
    {
        IDataRepository _dataObject = new DataRepository();
        //array for return value
        string[] a = new string[5];
       
        Merchant merchant = SessionWrapper.Merchant;

        PromotionCode pCode = new PromotionCode();
        pCode = new PromotionCode(_dataObject);
        pCode.SubscriptionId = merchant.SubscriptionHistories.ElementAt(0).SubscriptionId;
        pCode.Code = Code;
        if (merchant.SubscriptionHistories.ElementAt(0).PromotionId == null || (merchant.SubscriptionHistories.ElementAt(0).PromotionId == 0))
        {
            pCode.GetPromotionCodeByCode();
        }
       
        decimal NetAmount = Convert.ToDecimal(merchant.SubscriptionHistories.ElementAt(0).NetAmount);
        decimal discount = Convert.ToDecimal(merchant.SubscriptionHistories.ElementAt(0).Discount);
        decimal Total = Convert.ToDecimal(merchant.SubscriptionHistories.ElementAt(0).TotalAmount);

        DateTime ExpiryDate = DateTime.Now;
        ExpiryDate = Convert.ToDateTime(HttpContext.Current.Session["ExpiryDate"]);
        //x
        try
        {
            //if (merchant.SubscriptionHistories.ElementAt(0).PromotionId ==null)
            //{
            if (pCode.Id > 0)
            {
                if (pCode.AllowUser > 0)
                {
                    if (pCode.AllowUser > pCode.UsedCount)
                    {
                        if (pCode.DiscountType == (Int32)EnumClass.Enums.Discount.Rate)
                        {
                            discount = Convert.ToDecimal((Total * pCode.Discount) / 100);
                        }
                        else
                        {
                            discount = Convert.ToDecimal(pCode.Discount);

                        }
                    }
                }
                else
                {
                    if (pCode.DiscountType == (Int32)EnumClass.Enums.Discount.Rate)
                    {
                        discount = Convert.ToDecimal((Total * pCode.Discount) / 100);
                    }
                    else
                    {
                        discount = Convert.ToDecimal(pCode.Discount);
                    }
                }
                if (pCode.DiscountType == (Int32)EnumClass.Enums.Discount.Month)
                {
                    ExpiryDate = ExpiryDate.AddMonths(Convert.ToInt32(pCode.Discount));
                    discount = 0;
                }
            }
           // }
            NetAmount = Total - discount;

            a[0] = NetAmount.ToString();
            a[1] = discount.ToString();
            a[2] = ExpiryDate.ToString("dd/MM/yyyy");
            a[3] = pCode.Id.ToString();

            //assign month info is discount type is month
            if (pCode.DiscountType == (Int32)EnumClass.Enums.Discount.Month)
                a[4] = "(" + pCode.Discount + " Month Free)";
            else
                a[4] = "";

           
            if (pCode.Id != 0)
                merchant.SubscriptionHistories.ElementAt(0).PromotionId = pCode.Id;
            //else
            //    merchant.SubscriptionHistories.ElementAt(0).PromotionId = null;


            merchant.SubscriptionHistories.ElementAt(0).TotalAmount = Total;
            merchant.SubscriptionHistories.ElementAt(0).Discount = discount;
            merchant.SubscriptionHistories.ElementAt(0).NetAmount = NetAmount;
            merchant.SubscriptionHistories.ElementAt(0).ExpiryDate = ExpiryDate;

            SessionWrapper.Merchant = merchant;


            //return pCode.Id.ToString();
            return a;
        }
        catch (Exception ex)
        {
            a[0] = ex.Message;
            return a;

        }
    }
    #endregion

    #region Binddata
    private void BindData()
    {
        Merchant merchant = SessionWrapper.Merchant;

        //bind common info if mearchnt id >0  or not
        lblContactName.Text = merchant.Name;
        txtContactName.Text = merchant.Name;
      //  lblBillingName.Text = " ("+merchant.Name+")";
       
        #region BindState
        //Bind State
        State state = new State();
        state = new State(_dataObject);
        List<State> states = new List<State>();
        state.CountryId = (Int32)EnumClass.Enums.Country.India;
        states = state.GetStateByCountryId();
        drpState.DataSource = states;
        drpState.DataBind();
        drpState.Items.Insert(0, new ListItem("Select", "0"));
        drpCity.Items.Insert(0, new ListItem("Select", "0"));
        #endregion

        #region assign info in label and assign total and discount in merchant object

        Subscription subscription = new Subscription(_dataObject);
        subscription.Id = merchant.SubscriptionHistories.ElementAt(0).SubscriptionId;
        subscription.GetSubscriptionById();

        lblSubscription.Text = subscription.PlanName;
        lblDuration.Text = subscription.Duration + " Month";
        lblGrandTotal.Text = (merchant.SubscriptionHistories.ElementAt(0).TotalAmount - merchant.SubscriptionHistories.ElementAt(0).Discount).ToString();
        lblSubTotal.Text = merchant.SubscriptionHistories.ElementAt(0).TotalAmount.ToString();
        lblDiscount.Text = merchant.SubscriptionHistories.ElementAt(0).Discount.ToString();

        lblStartDate.Text = merchant.SubscriptionHistories.ElementAt(0).StartDate.ToString("dd/MM/yyyy"); 
        lblOldExpiryDate.Text = merchant.SubscriptionHistories.ElementAt(0).ExpiryDate.ToString("dd/MM/yyyy");

        //high light label if month is extended 
        if (merchant.SubscriptionHistories.ElementAt(0).PromotionId != null && merchant.SubscriptionHistories.ElementAt(0).PromotionId != 0)
        {
            PromotionCode pCode = new PromotionCode();
            pCode = new PromotionCode(_dataObject);
            pCode.Id = Convert.ToInt32(merchant.SubscriptionHistories.ElementAt(0).PromotionId);
            pCode.GetPromotionCodeById();

            if (pCode.DiscountType == (Int32)EnumClass.Enums.Discount.Month)
            {
                
                lblOldExpiryDate.Text = lblOldExpiryDate.Text + "( " + pCode.Discount + " Month Free)";
                lblOldExpiryDate.CssClass = "expiryDate";
            }
        }

        if (merchant.Id > 0)
        {
            Address address = new Address(_dataObject);
            address.MerchantId = merchant.Id;
            List<Address> addresses = address.GetAddressByMerchantId();
            addresses = addresses.Where(w => w.IsmasterAddress == true).ToList();

            lblAddressLine1.InnerText = addresses.ElementAt(0).Address1;
            lblAddressLine2.InnerText = addresses.ElementAt(0).Address2;
            lblCity.Text = addresses.ElementAt(0).City.Name;
            lblPincode.Text = addresses.ElementAt(0).Pincode;

            //assign in txt
            txtAddress1.Text = addresses.ElementAt(0).Address1;
            txtAddress2.Text = addresses.ElementAt(0).Address2;
            drpState.SelectedValue = addresses.ElementAt(0).StateId.ToString();
            txtPostalCode.Text = addresses.ElementAt(0).Pincode;
           
            //bind city
            City city = new City();
            List<City> cities = new List<City>();
            city = new City(_dataObject);
            city.StateId = Convert.ToInt32(drpState.SelectedValue);
            cities = city.GetCityByStateId();
            drpCity.DataSource = cities;
            drpCity.DataBind();
            drpCity.SelectedValue = addresses.ElementAt(0).CityId.ToString();

            merchant.Addresses.Add(addresses.ElementAt(0));
            SessionWrapper.Merchant = merchant;

        }
        else
        {
            City city = new City();
            List<City> cities = new List<City>();
            city = new City(_dataObject);
            city.Id = merchant.Addresses.ElementAt(0).CityId;

            lblAddressLine1.InnerText = merchant.Addresses.ElementAt(0).Address1;
            lblAddressLine2.InnerText = merchant.Addresses.ElementAt(0).Address2;
            lblPincode.Text = merchant.Addresses.ElementAt(0).Pincode;
            lblContactNo.InnerText = merchant.Mobile;
            city.GetCityById();
            lblCity.Text = city.Name;

            //assign in txt
            txtAddress1.Text = merchant.Addresses.ElementAt(0).Address1;
            txtAddress2.Text = merchant.Addresses.ElementAt(0).Address2;
            drpState.SelectedValue = merchant.Addresses.ElementAt(0).StateId.ToString();
            txtPostalCode.Text = merchant.Addresses.ElementAt(0).Pincode;
            //bind city


            city.StateId = Convert.ToInt32(drpState.SelectedValue);
            cities = city.GetCityByStateId();
            drpCity.DataSource = cities;
            drpCity.DataBind();
            drpCity.SelectedValue = merchant.Addresses.ElementAt(0).CityId.ToString();
        }
        lblCityId.Text = drpCity.SelectedValue;
        SessionWrapper.Merchant = merchant;
        HttpContext.Current.Session["ExpiryDate"] = merchant.SubscriptionHistories.ElementAt(0).ExpiryDate;

        #endregion


    }
    #endregion

    #region Next
    protected void OnNext(object sender, EventArgs e)
    {
        //enter data in merchant's table
        Merchant merchant = new Merchant(_dataObject);
        merchant = SessionWrapper.Merchant;
        if (merchant.Id > 0)
        {
            SubscriptionHistory subHistory = new SubscriptionHistory(_dataObject);
            subHistory.MerchantId = merchant.SubscriptionHistories.ElementAt(0).MerchantId;
            subHistory.SubscriptionId = merchant.SubscriptionHistories.ElementAt(0).SubscriptionId; ;
            subHistory.StartDate = merchant.SubscriptionHistories.ElementAt(0).StartDate; ;
            subHistory.PromotionId = merchant.SubscriptionHistories.ElementAt(0).PromotionId;
            subHistory.TotalAmount = merchant.SubscriptionHistories.ElementAt(0).TotalAmount;
            subHistory.Discount = merchant.SubscriptionHistories.ElementAt(0).Discount;
            subHistory.NetAmount = merchant.SubscriptionHistories.ElementAt(0).NetAmount;
            subHistory.ExpiryDate = merchant.SubscriptionHistories.ElementAt(0).ExpiryDate;
            subHistory.IsDeleted = merchant.SubscriptionHistories.ElementAt(0).IsDeleted; ;
            subHistory.CreatedDate = merchant.SubscriptionHistories.ElementAt(0).CreatedDate; ;
            subHistory.IpAdded = merchant.SubscriptionHistories.ElementAt(0).IpAdded; ;
            subHistory.Discount = merchant.SubscriptionHistories.ElementAt(0).Discount; ;
            subHistory.IsActive = merchant.SubscriptionHistories.ElementAt(0).IsActive; ;
            subHistory.Create();
        }
        else
            merchant.Create();

        //Response.Redirect("~/PaymentGateway.aspx");

    }
    #endregion

    #region update
    protected void OnUpdateBillingInformation(object sender, EventArgs e)
    {
        Merchant merchant = SessionWrapper.Merchant;

        //get city name
        List<City> cities = new List<City>();
        City city = new City();
        city = new City(_dataObject);
        city.Id = Convert.ToInt32(lblCityId.Text);
        city.GetCityById();



        if (merchant.Id > 0)
        {
            //update billing info
            Address address = new Address(_dataObject);
            address.Id = merchant.Addresses.ElementAt(0).Id;
            address.Address1 = txtAddress1.Text;
            address.Address2 = txtAddress2.Text;
            address.Pincode = txtPostalCode.Text;
            address.StateId = Convert.ToInt32(drpState.SelectedValue);
            address.CityId = Convert.ToInt32(lblCityId.Text);
            address.Update();

            //update contactname
            merchant.Name = txtContactName.Text;
            merchant.UpdateContactName();

            updateDisplayBillingInformation(address.Address1, address.Address2, address.Pincode, city.Name,txtContactName.Text);
        }
        else
        {
            merchant.Addresses.ElementAt(0).Address1 = txtAddress1.Text;
            merchant.Addresses.ElementAt(0).Address2 = txtAddress2.Text;
            merchant.Addresses.ElementAt(0).Pincode = txtPostalCode.Text;
            merchant.Addresses.ElementAt(0).StateId = Convert.ToInt32(drpState.SelectedValue);
            merchant.Addresses.ElementAt(0).CityId = Convert.ToInt32(lblCityId.Text);
            merchant.Name = txtContactName.Text;
            SessionWrapper.Merchant = merchant;
            updateDisplayBillingInformation(txtAddress1.Text, txtAddress2.Text, txtPostalCode.Text, city.Name, txtContactName.Text);
        }
        //bind city once again( i have bind this because city is lost after postback)
        city.StateId = Convert.ToInt32(drpState.SelectedValue);
        cities = city.GetCityByStateId();
        drpCity.DataSource = cities;
        drpCity.DataBind();
        drpCity.SelectedValue =lblCityId.Text;



        
        ScriptManager.RegisterClientScriptBlock(this,GetType(),"","closePopUp();",true);
    }
    private void updateDisplayBillingInformation(string address1, string address2, string picode, string cityname,string name)
    {
        lblAddressLine1.InnerText = address1;
        lblAddressLine2.InnerText = address2;
        lblPincode.Text = picode;
        lblCity.Text = cityname;
        lblContactName.Text = name;
    }
    #endregion


}